package org.zjx.log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * LogRotationHandler实现了日志轮转，当日志文件超过指定大小时，自动轮转日志文件。
 */
public class LogRotationHandler implements LogHandler {
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;  // 最大文件大小为10MB
    private String logFilePath;

    public LogRotationHandler(String logFilePath) {
        this.logFilePath = logFilePath;
    }

    @Override
    public void handleLog(LogLevel level, String message) {
        try {
            File logFile = new File(logFilePath);
            if (logFile.exists() && logFile.length() > MAX_FILE_SIZE) {
                rotateLogFile();
            }
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(logFilePath, true))) {
                writer.write("[" + level + "] " + message);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void rotateLogFile() throws IOException {
        String timestamp = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
        String newLogFilePath = logFilePath + "." + timestamp;
        Files.move(Paths.get(logFilePath), Paths.get(newLogFilePath), StandardCopyOption.REPLACE_EXISTING);
        System.out.println("Log file rotated: " + newLogFilePath);
    }
}

